package algorithm.leetcode;

import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;

/**
 * @program: util
 * @description:找到字符串中匹配数组给定字符串的所有下标
 * @author: zhouliangliang
 * @create: 2021-04-20 19:23
 **/
public class FindAllString {


    private void findAll(String array[], String str) {
        Map<String, Integer> map = new HashMap<>();

        Stream.of(array).forEach(item->{
            map.put(item, map.getOrDefault(item, 0) + 1);
        });

//        map.entrySet().stream().forEach(entry->{
//            System.out.println(entry.getKey());
//            System.out.println(entry.getValue());
//        });



        int arrayLength = array.length;
        int itemLength = array[0].length();
        for(int i=0; i<=str.length() - arrayLength*itemLength; i++) {
            StringBuilder result = new StringBuilder();
            Map<String, Integer> tmpMap = new HashMap<>();

            int nextIndex = i + itemLength;
            String subStr = str.substring(i, nextIndex);

            int nums = 0;
            while (map.containsKey(subStr)) {
                result.append(nextIndex - itemLength).append(",");
                nums ++;
                tmpMap.put(subStr, tmpMap.getOrDefault(subStr,0) + 1);
                if(tmpMap.get(subStr) > map.get(subStr)) {
                    break;
                }
                subStr = str.substring(nextIndex, nextIndex + itemLength);
                nextIndex = nextIndex + itemLength;
            }

            if(nums == array.length) {
                System.out.println(result.toString());
            }
        }
    }

    public static void main(String[] args) {
        String array[] = new String[]{"foo","bar"};
        String str = "barfoothefoobarman";
        new FindAllString().findAll(array, str);
    }
}
